package com.jpress.ejb;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jpress.model.Enquete;
import com.jpress.remote.EnqueteRemote;

@Stateless(mappedName="bean/enquete")
public class EnqueteEJB implements EnqueteRemote{
	
	@PersistenceContext(unitName="jpressEE")
	private EntityManager entityManager;	

	@Override
	public void inserir(Enquete enquete) throws Exception {
		try {
			entityManager.persist(enquete);
		} catch (Exception e) {
			throw e;
		}		
	}

	@Override
	public void atualizar(Enquete enquete) throws Exception {
		try {
			entityManager.merge(enquete);
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public void excluir(Enquete enquete) throws Exception {
		try {
			enquete = entityManager.merge(enquete);
			entityManager.remove(enquete);
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public Enquete findByCodigo(int codigo) {
		Query query = entityManager.createNamedQuery("Enquete.findByCodigo");
		query.setParameter("codigo", codigo);
		@SuppressWarnings("unchecked")
		List<Enquete> resultado = (List<Enquete>) query.getResultList();
		if(resultado.size() == 1)
			return resultado.get(0);
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Enquete> findAll() {
		return (List<Enquete>) entityManager.createNamedQuery("Enquete.findAll").getResultList();
	}

}
